import React from 'react'
import { connect } from 'dva'
import { Form ,Modal,message,Upload,Button} from 'antd'
import { Link, hashHistory } from 'dva/router'
import config from 'config/config'
import $ from 'jquery'
import FlagBtn from 'widget/FlagBtn/FlagView'
import { mapStateToProps } from 'utils/view_utils'
import styles from './taskListStyle.less'
import ListPage from 'widget/PageTmpl/ListPage'
import classnames from 'classnames/bind';
import moment from 'moment'
let cx=classnames.bind(styles);
const confirm = Modal.confirm;

function timestampToTime(timestamp) {
  var date = new Date(timestamp);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
  var Y = date.getFullYear() + '-';
  var M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
  var D = (date.getDate() < 10 ? '0'+date.getDate() : date.getDate()) + ' ';
  var h = (date.getHours() < 10 ? '0'+date.getHours() : date.getHours()) + ':';
  var m = (date.getMinutes() < 10 ? '0'+date.getMinutes() : date.getMinutes()) + ':';
  var s = (date.getSeconds() < 10 ? '0'+date.getSeconds() : date.getSeconds());
    return Y+M+D+h+m+s;
}

const taskListView = function({dispatch, model, form}) {
  // 表单的子函数
  // const {resetFields, getFieldDecorator, validateFields, setFieldsValue} = form
  // 取出model对象，命名空间
  const { modelObj, namespace } = model
  // modelObj.xxx获取model中状态机的值
  let {submitFeikongLoading,backLoading,submitLoading,biz,id,products,areaList,otherQuery} = modelObj
 
  let pageProps = {
    // ---------- 界面部分 ----------
    ui: {
      // 页面接口地址
      api_url: `zituo-admin/a/task/zituoTask`,
      // 接口方式
      method: "POST", 
      app: "",
      // 接口参数
      params: {
        pageSize:10,
        pageNo:1,
        areaId:otherQuery.areaId && otherQuery.areaId != ""?otherQuery.areaId:"",
        projectId:otherQuery.projectId && otherQuery.projectId != ""?otherQuery.projectId:"",
        // areaId: 'A7319161253',
        // projectId: '0005257B-316A-4A9C-887E-C699D845BBFE',
        // status: '2',
        },
      // 模拟数据 - 用于开发需要，若填充了上面的api_url之后，请将此项设置为null
      // "mockData": mockData,
      mockData: null,
      // 查询栏
      search_bar: {
        fields: [
          {
            en_name: 'areaId',
            zh_name: '区域',
            elem_type: 'Select',
            elem_valid_type: 'string',
            cmpt_items: areaList,
          },
          {
            en_name: 'projectId',
            zh_name: '项目',
            elem_type: 'SelectFilter',
            elem_valid_type: 'string',
            showSearch: true,
            cmpt_items: products,
            onFocus:()=>{
              if(biz.queryForm && biz.queryForm.areaId){ 
                dispatch({
                  type: `${namespace}/filterProjectList`,
                  payload: {areaId}
                })
              }
            },
          },
          {
            en_name: 'createrName',
            zh_name: '任务发布人',
            elem_type: 'Input',
            elem_valid_type: 'string',
          },
          {
            en_name: 'status',
            zh_name: '任务状态',
            elem_type: 'Select',
            elem_valid_type: 'string',
            cmpt_items: [
              {
                value: '0',
                label: '未进行'
             }, 
              {
                  value: '1',
                  label: '进行中'
              },
              {
                  value: '2',
                  label: '已结束'
              }
            ],
          },
          {
            en_name: 'channel',
            zh_name: '渠道',
            elem_type: 'Select',
            elem_valid_type: 'string',
            cmpt_items: [
              {
                  value: '行销自拓',
                  label: '行销自拓'
               }
          ],
          },
          {
            en_name: 'createTime',
            zh_name: '起止日期',
            elem_type: 'Date',
            format: 'YYYY-MM-DD HH:mm:ss',
            query_format: "YYYY-MM-DD HH:mm:ss",   // 请求参数, 当请求参数和显示时格式不同可通过该参数区分
            double: true,  // 日期范围组件 使用"YYYY-MM-DD HH:mm:ss"格式时, 显示不全时可使用该参数, 将占据两格位置
            split_keys: ['startTime', 'endTime'],
            elem_valid_type: 'string'
          },
        ],
        searchHandler: () => { // 自定义搜索按钮回调函数，点击搜索时触发
          console.log('search click')
        },
        resetHandler: () => { // 自定义重置按钮回调函数，点击重置时触发
          console.log('reset click')
        },
        searchCallback: params => { // 自定义搜索完成后的后调函数, 搜索完成后触发, 并将本次搜索的参数传入
          console.log('search finish', params)
        },
        pasteTargetList: [  // 列表组件中将输入框的en_name作为默认id(也可以通过id另外设置)
          'channel',  // 将需要粘贴事件拦截的输入框id以数组的形式传入, 该参数对应PasteFromClipboard组件的targetList参数
        ]
      },
      // 数据表格  序号 是否生效 项目名称  佣金方案名称 方案生效日期 方案失效日期 审批人 审批通过日期   提交人 提交日期  创建人 创建日期
      table:
        {
          status_params: "status=0",
          status_text: "全部",
          // 表头字段列表
          scroll: { x: 2200},
          fields: [
            {
              en_name: "ruleNo",
              zh_name: "编号",
              width: 60,
              render: (a, item, index, d, e, f) => {
                return index+1
              },
            },
            {
              en_name: "areaName",
              zh_name: "区域",
            },
            {
              en_name: "projectName",
              zh_name: "项目",
            },
            {
              en_name: "channel",
              zh_name: "渠道",
            },
            {
              en_name: "taskName",
              zh_name: "任务名称",
            },
            {
              en_name: "addressName",
              zh_name: "任务地址",
            },
            {
              en_name: "createrName",
              zh_name: "任务发布人名称",
            },
            {
              en_name: "startTime",
              zh_name: "开始时间",
              render:(a, item, index, d, e, f)=>{
                if(item.startTime){
                  return timestampToTime(item.startTime)
                }else{
                  return ''
                }
              }
            },
            {
              en_name: "endTime",
              zh_name: "结束时间",
              render:(a, item, index, d, e, f)=>{
                if(item.endTime){
                  return timestampToTime(item.endTime)
                }else{
                  return ''
                }
              }
            },
            {
              en_name: "methodName",
              zh_name: "拓客方式",
            },
            {
              en_name: "status",
              zh_name: "状态",
              render:(a, item, index, d, e, f)=>{
                if(item.status == 0){
                  return '未进行'
                }else if(item.status == 1){
                  return '进行中'
                }else if(item.status == 2){
                  return '已完成'
                }
              }
            },
            {
              en_name: "edit",
              zh_name: "操作",
              width:120,
              fixed:'right',
              render: (a, item, index, d, e, f) => {
                return (
                  <span>
                      <FlagBtn node={<a onClick={() => checkOrEditSkip('check',item)}>任务详情<span className="ant-divider" /></a>} btnId={''}> </FlagBtn>
                      <FlagBtn node={<a onClick={() => checkOrEditSkip('edit',item)}>编辑<span className="ant-divider" /></a>} btnId={''}> </FlagBtn>
                      <FlagBtn node={<a onClick={() => deleteContent('end',item)}>结束<span className="ant-divider" /></a>} btnId={''}> </FlagBtn>
                      <FlagBtn node={<a onClick={() => deleteContent('del',item)}>删除</a>} btnId={''}> </FlagBtn>
                  </span>
                )
              },
            }
          ],
        },
      // 操作栏
      action_bar: [
        {
          label: "新建任务",
          type: "primary",
          onClick: (e) =>{
            hashHistory.push({
              pathname: '/home/expandManage/taskAdd',
              query: {}
            });
          }
        }
      ]
    },
  }
  
  //查看，编辑
  function checkOrEditSkip(type,item){
    if(item&&item.status == '1'&&type == 'edit'){
      message.warn('进行中的任务不可编辑')
      return false
    }
    if(item&&item.status == '2'&&type == 'edit'){
      message.warn('已完成的任务不可编辑')
      return false
    }
    if(type == 'check'){
      hashHistory.push({
        pathname: '/home/expandManage/taskInfo',
        query: {actionType: type, id:item.id }
      })
    }
    if(type == 'edit'){
      hashHistory.push({
        pathname: '/home/expandManage/taskAdd',
        query: {actionType: type, id:item.id }
      })
    }
  }
  //结束，删除
  function deleteContent(type,item){
    if(item&&item.status == '1'&&type == 'del'){
      message.warn('进行中的任务不可删除')
      return false
    }
    if(item&&item.status == '2'&&type == 'del'){
      message.warn('已完成的任务不可删除')
      return false
    }
    if(item&&item.status == '2'&&type == 'end'){
      message.warn('任务已完成，无需此操作')
      return false
    }
    dispatch({
      type: `${namespace}/deleteContent`,
      payload: {actionType: type, id:item.id}
    })
  }

  if (!!modelObj.biz) {
		pageProps.biz = modelObj.biz
		pageProps.biz.syncBackCbf = (biz) => {
			dispatch({
				type: `${namespace}/updateStore`,
				payload: { biz }
			})
		}
  }

  return (
    <div className={cx('pageLayout')}>
      <ListPage pageProps={pageProps}/>
    </div>
  )
}
// 连接视图(view)和模型(model)
export default connect(mapStateToProps)(Form.create()(taskListView))
